package cosplay.Controller;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cosplay.Beans.Albums;
import cosplay.Beans.Tags;
import cosplay.DAO.AlbumDAOImpl;
import cosplay.DAO.PhotoDAOImpl;
import cosplay.DAO.TagDAOImpl;
import cosplay.DAO.UserDAOImpl;
import cosplay.Services.CacheServices;
import cosplay.Services.CommonServices;
import cosplay.Services.TagServices;

@Controller
public class AlbumController extends MultiActionController{
	@Autowired
	AlbumDAOImpl albumdao;
	@Autowired
	UserDAOImpl userdao;
	@Autowired
	PhotoDAOImpl photodao;
	@Autowired
	TagDAOImpl tagdao;
	private Cache cache=CacheManager.create().getCache("COSPLAY_CACHE");
	
	@RequestMapping(value="/addalbum.htm",method=RequestMethod.GET)
	protected ModelAndView handelShowAdd(HttpServletRequest req,HttpServletResponse res) throws Exception
	{
		ModelMap model =new ModelMap();
		model.addAttribute("target","addalbum.htm");
		model.addAttribute("message","please enter infomation");
		return new ModelAndView("albummodify","model",model);
	}
	
	@RequestMapping(value="/addalbum.htm",method=RequestMethod.POST)
	protected ModelAndView handelActAdd(HttpServletRequest req,HttpServletResponse res) throws Exception
	{
		Albums album=getAlbumFromRequest(req);
		int id=albumdao.add(album);
		ModelMap model=new ModelMap();
		if (id>0)
		{
			res.setIntHeader("sucess", 1);
			//res.sendRedirect("/adminalbum.htm?message=add%20succesed");
		}
		else
		{
			res.setIntHeader("sucess", 0);
			model.addAttribute("message","add failed please try again later");
		}
		model.addAttribute("target","editalbum.htm");
		model.addAttribute("album",album);
		model.addAttribute("tags",TagServices.getStringFromTagList(album.getTags()));
		return new ModelAndView("albummodify","model",model);
	}
	
	@RequestMapping(value="/editalbum.htm",method=RequestMethod.GET)
	protected ModelAndView handelShowEdit(HttpServletRequest req,HttpServletResponse res) throws Exception
	{
		int userid=0;
		Albums album=new Albums();
		if (CommonServices.getLoggedUsername(req)!=null)
			userid=userdao.getByName(CommonServices.getLoggedUsername(req)).getId();
		int albumid=CommonServices.getIDFromRequest(req, "albumid");
		if (albumdao.get(albumid).getUserID()==userid)
		{
			album=albumdao.get(albumid);
		}
		ModelMap model =new ModelMap();
		model.addAttribute("target","editalbum.htm");
		model.addAttribute("message","please enter infomation");
		model.addAttribute("album",album);
		model.addAttribute("tags",TagServices.getStringFromTagList(album.getTags()));
		return new ModelAndView("albummodify","model",model);
	}
	
	@RequestMapping(value="/editalbum.htm",method=RequestMethod.POST)
	protected ModelAndView handelActEdit(HttpServletRequest req,HttpServletResponse res) throws Exception
	{
		Albums album=getAlbumFromRequest(req);
		ModelMap model=new ModelMap();
		if (albumdao.edit(album, CommonServices.getIDFromRequest(req, "albumid")))
		{
			res.setIntHeader("sucess", 1);
			res.sendRedirect("adminalbum.htm?message=add%20succesed");
		}
		else
		{
			res.setIntHeader("sucess", 0);
			model.addAttribute("message","edit failed please try again later");
		}
		model.addAttribute("target","editalbum.htm");
		model.addAttribute("album",album);
		model.addAttribute("tags",TagServices.getStringFromTagList(album.getTags()));
		return new ModelAndView("albummodify","model",model);
	}
	
	@RequestMapping(value="/delalbum.htm")
	protected ModelAndView handelActDel(HttpServletRequest req ,HttpServletResponse res) throws Exception
	{
		int id=CommonServices.getIDFromRequest(req, "albumid");
		if(albumdao.delete(id))
		{
			res.setIntHeader("sucess", 1);
			res.sendRedirect("/adminalbum.htm?message=delete%20sucess");
		}
		else
		{
			res.setIntHeader("sucess", 0);
			res.sendRedirect("adminalbum.htm?message=delete%20failed");
		}
		return null;
	}
	
	@RequestMapping(value="/adminalbum.htm")
	protected ModelAndView handelShowAdmin (HttpServletRequest req,HttpServletResponse res)throws Exception
	{
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		if (userdao.getByName(CommonServices.getLoggedUsername(req)).getUserRole().equals("ROLE_ADMIN"))
		{
			model.addAttribute("target","adminalbumpage.htm");
		}
		else
		{
			int uid =userdao.getByName(CommonServices.getLoggedUsername(req)).getId();
			model.addAttribute("target","adminalbumpage.htm?userid="+uid+"");
		}
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		return new ModelAndView("listajax","model",model);
	}
	
	@RequestMapping(value="/adminalbumpage.htm")
	protected ModelAndView handelShowAdminContent (HttpServletRequest req, HttpServletResponse res) throws Exception
	{
		String filtername="getallalbum";
		String sessionid=req.getSession().getId();
		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
			CacheServices.insertToCache(cache, filtername, sessionid, albumdao.getAll(), 10);
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> albumids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Albums> albums=new ArrayList<Albums>();
		for(int i:albumids)
		{
			albums.add(albumdao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=albums.size();
		ModelMap model=new ModelMap();
		model.addAttribute("album",albums);
		model.addAttribute("pageresultcount",pageresultcount);
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("albumadmin","model",model);
	}
	
	@RequestMapping(value="/listuseralbum.htm")
	protected ModelAndView handelShowUserList (HttpServletRequest req,HttpServletResponse res)throws Exception
	{
		int uid=CommonServices.getIDFromRequest(req, "userid");
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		model.addAttribute("target","/listuseralbumpage.htm?userid="+uid+"");
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		return new ModelAndView("listajax","model",model);
	}
	
	@RequestMapping(value="/listuseralbumpage.htm")
	protected ModelAndView handelShowUserListContent (HttpServletRequest req, HttpServletResponse res) throws Exception
	{
		int uid =CommonServices.getIDFromRequest(req, "userid");
		String filtername="getalbum?userid="+uid+"";
		String sessionid=req.getSession().getId();
		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
		{
			List<Integer> test=albumdao.getByUser(uid);
			test.addAll(test);
			test.addAll(test);
			CacheServices.insertToCache(cache, filtername, sessionid, test, 10);
			//CacheServices.insertToCache(cache, filtername, sessionid, albumdao.getByUser(uid), 10);
		}
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> albumids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Albums> albums=new ArrayList<Albums>();
		for(int i:albumids)
		{
			albums.add(albumdao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=albums.size();
		ModelMap model=new ModelMap();
		model.addAttribute("album",albums);
		model.addAttribute("pageresultcount",pageresultcount);
		model.addAttribute("resultcount",resultcount);
		model.addAttribute("pagecount",pagecount);
		model.addAttribute("currentpage",page);
		model.addAttribute("haspre",(page>1));
		model.addAttribute("hasnext",(page<pagecount));
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("showcaseindetail","model",model);
	}
	
	@RequestMapping(value="/listtagalbum.htm")
	protected ModelAndView handelShowTagList (HttpServletRequest req,HttpServletResponse res)throws Exception
	{
		int tid=CommonServices.getIDFromRequest(req, "tagid");
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		model.addAttribute("target","/listtagalbumpage.htm?tagrid="+tid+"");
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		return new ModelAndView("listajax","model",model);
	}
	
	@RequestMapping(value="/listtagalbumpage.htm")
	protected ModelAndView handelShowTagListContent (HttpServletRequest req, HttpServletResponse res) throws Exception
	{
		int tid =CommonServices.getIDFromRequest(req, "tagid");
		String filtername="getalbum?tagid="+tid+"";
		String sessionid=req.getSession().getId();
		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
			CacheServices.insertToCache(cache, filtername, sessionid, albumdao.getByUser(tid), 10);
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> albumids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Albums> albums=new ArrayList<Albums>();
		for(int i:albumids)
		{
			albums.add(albumdao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=albums.size();
		ModelMap model=new ModelMap();
		model.addAttribute("album",albums);
		model.addAttribute("pageresultcount",pageresultcount);
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("albumlist","model",model);
	}
	
	@RequestMapping(value="/listuploadalbum.htm")
	protected ModelAndView handelShowUploadList (HttpServletRequest req,HttpServletResponse res)throws Exception
	{
		Date start=CommonServices.getDateFromRequest(req, "startdate");
		Date end=CommonServices.getDateFromRequest(req, "enddate");
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		model.addAttribute("target","/listuploadalbumpage.htm?startdate="+start.toString()+"&enddate="+end.toString()+"");
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		return new ModelAndView("listajax","model",model);
	}
	
	@RequestMapping(value="/listuploadalbumpage.htm")
	protected ModelAndView handelShowUploadListContent (HttpServletRequest req, HttpServletResponse res) throws Exception
	{
		Date start=CommonServices.getDateFromRequest(req, "startdate");
		Date end=CommonServices.getDateFromRequest(req, "enddate");
		String filtername="getalbum?start="+start+"&end="+end+"";
		String sessionid=req.getSession().getId();
		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
			CacheServices.insertToCache(cache, filtername, sessionid, albumdao.getByUpload(start, end), 10);
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> albumids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Albums> albums=new ArrayList<Albums>();
		for(int i:albumids)
		{
			albums.add(albumdao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=albums.size();
		ModelMap model=new ModelMap();
		model.addAttribute("album",albums);
		model.addAttribute("pageresultcount",pageresultcount);
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("albumlist","model",model);
	}
	
	@RequestMapping(value="/lastuploadalbum.htm")
	protected ModelAndView handelShowLastUploadList (HttpServletRequest req,HttpServletResponse res)throws Exception
	{
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		model.addAttribute("target","/lastuploadalbumpage.htm");
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		return new ModelAndView("listajax","model",model);
	}
	
	@RequestMapping(value="/lastuploadalbumpage.htm")
	protected ModelAndView handelShowLastUploadListContent (HttpServletRequest req, HttpServletResponse res) throws Exception
	{
		String filtername="getalbumlastupload";
		String sessionid=req.getSession().getId();
		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
			CacheServices.insertToCache(cache, filtername, sessionid, albumdao.getLastUpload(), 10);
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> albumids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Albums> albums=new ArrayList<Albums>();
		for(int i:albumids)
		{
			albums.add(albumdao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=albums.size();
		ModelMap model=new ModelMap();
		model.addAttribute("album",albums);
		model.addAttribute("pageresultcount",pageresultcount);
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("albumlist","model",model);
	}
	
	@RequestMapping(value="/mostviewedalbum.htm")
	protected ModelAndView handelShowMostViewedList (HttpServletRequest req,HttpServletResponse res)throws Exception
	{
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		model.addAttribute("target","/mostviewedalbumpage.htm");
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		return new ModelAndView("listajax","model",model);
	}
	
	@RequestMapping(value="/mostviewedalbumpage.htm")
	protected ModelAndView handelShowMostViewedListContent (HttpServletRequest req, HttpServletResponse res) throws Exception
	{
		String filtername="getalbummostviewed";
		String sessionid=req.getSession().getId();
		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
			CacheServices.insertToCache(cache, filtername, sessionid, albumdao.getMostViewed(), 10);
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> albumids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Albums> albums=new ArrayList<Albums>();
		for(int i:albumids)
		{
			albums.add(albumdao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=albums.size();
		ModelMap model=new ModelMap();
		model.addAttribute("album",albums);
		model.addAttribute("pageresultcount",pageresultcount);
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("albumlist","model",model);
	}
	
	@RequestMapping(value="/mostcommentedalbum.htm")
	protected ModelAndView handelShowMostCommentedList (HttpServletRequest req,HttpServletResponse res)throws Exception
	{
		ModelMap model=new ModelMap();
		model.addAttribute("message",CommonServices.getMessageFromRequest(req));
		model.addAttribute("target","/mostcommentedalbumpage.htm");
		model.addAttribute("page",CommonServices.getPageFromRequest(req));
		return new ModelAndView("listajax","model",model);
	}
	
	@RequestMapping(value="/mostcommentedalbumpage.htm")
	protected ModelAndView handelShowMostCommentedListContent (HttpServletRequest req, HttpServletResponse res) throws Exception
	{
		String filtername="getalbummostcommented";
		String sessionid=req.getSession().getId();
		if (CacheServices.getFromCache(cache, sessionid, filtername, 1)==null)
			CacheServices.insertToCache(cache, filtername, sessionid, albumdao.getMostComment(), 10);
		int page=CommonServices.getPageFromRequest(req);
		List<Integer> albumids=CacheServices.getFromCache(cache, sessionid, filtername, page);
		List<Albums> albums=new ArrayList<Albums>();
		for(int i:albumids)
		{
			albums.add(albumdao.get(i));
		}
		int resultcount=CacheServices.getCountFromCache(cache, sessionid, filtername);
		int pagecount=CommonServices.getPageFromCount(resultcount);
		int pageresultcount=albums.size();
		ModelMap model=new ModelMap();
		model.addAttribute("album",albums);
		model.addAttribute("pageresultcount",pageresultcount);
		res.addIntHeader("resultcount", resultcount);
		res.addIntHeader("pagecount", pagecount);
		res.addIntHeader("currentpage", page);
		return new ModelAndView("albumlist","model",model);
	}
	
	private Albums getAlbumFromRequest(HttpServletRequest req)
	{
		Albums album=new Albums();
		if (CommonServices.getLoggedUsername(req)!=null)
			album.setUserID(userdao.getByName(CommonServices.getLoggedUsername(req)).getId());
		else
			return null;
		album.setCharacter(req.getParameter("character"));
		album.setCostume(req.getParameter("costume"));
		album.setDescription(req.getParameter("description"));
		album.setName(req.getParameter("name"));
		album.setPhotographer(req.getParameter("photographer"));
		album.setType(req.getParameter("type"));
		album.setId(CommonServices.getIDFromRequest(req, "albmid"));
		String tags=req.getParameter("tags");
		if (tags!=null)
		{
			List<Tags> newtags=new ArrayList<Tags>();
			for (String tag:tags.split(","))
			{
				if ((tag!=null)&&(!tag.equals("")))
				{
					Tags temptag=new Tags();
					int id=tagdao.getIDByWord(tag);
					if (id>0)
					{
						temptag=tagdao.get(id);
						newtags.add(temptag);
					}
					else
					{
						temptag.setSystem(false);
						temptag.setWord(tag);
						newtags.add(temptag);
					}
				}
			}
			album.setTags(newtags);
		}
		return album;
	}

}
